<template>
  <div class="app-container">
    <el-card class="page-container">
      <template #header>
        <div class="card-header">
          <h3>数据表管理</h3>
          <div class="header-actions">
            <el-button type="info" @click="handleImportSQL">
              <el-icon><Upload /></el-icon>
              导入SQL
            </el-button>
            <el-button type="success" @click="handleExportSQL">
              <el-icon><Download /></el-icon>
              导出SQL
            </el-button>
            <el-button type="primary" @click="handleAddTable">
              <el-icon><Plus /></el-icon>
              新增数据表
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-container">
        <el-form :model="searchForm" inline>
          <el-form-item label="表名">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入表名"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <el-table
        :data="filteredTables"
        stripe
        border
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="name" label="表名" width="200">
          <template #default="{ row }">
            <el-tag type="info">
              {{ row.name }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="comment" label="表注释" min-width="200" />

        <el-table-column label="字段数量" width="120" align="center">
          <template #default="{ row }">
            <div class="count-display">
              <el-icon class="count-icon" color="#409eff">
                <Grid />
              </el-icon>
              <span class="count-number">{{ row.fields?.length || 0 }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="关联关系" width="120" align="center">
          <template #default="{ row }">
            <div class="count-display">
              <el-icon class="count-icon" color="#67c23a">
                <Connection />
              </el-icon>
              <span class="count-number">{{ getRelationCount(row) }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="createdAt" label="创建时间" width="180" />
        <el-table-column prop="updatedAt" label="更新时间" width="180" />

        <el-table-column label="操作" width="300" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleConfigTable(row)"
            >
              <el-icon><Setting /></el-icon>
              配置字段
            </el-button>
            <el-button
              type="success"
              size="small"
              @click="handleViewRelations(row)"
            >
              <el-icon><Share /></el-icon>
              查看关联
            </el-button>
            <el-button
              type="warning"
              size="small"
              @click="handleEditTable(row)"
            >
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDeleteTable(row)"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      :close-on-click-modal="false"
      class="table-dialog"
    >
      <el-form
        ref="formRef"
        :model="tableForm"
        :rules="tableFormRules"
        label-width="80px"
      >
        <el-form-item label="表名" prop="name">
          <el-input
            v-model="tableForm.name"
            placeholder="请输入表名（英文）"
            :disabled="isEdit"
          />
        </el-form-item>
        <el-form-item label="表注释" prop="comment">
          <el-input
            v-model="tableForm.comment"
            placeholder="请输入表注释（中文描述）"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="handleSubmitTable">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- SQL导入对话框 -->
    <el-dialog
      v-model="sqlImportDialogVisible"
      title="SQL 导入"
      width="70%"
      :close-on-click-modal="false"
      class="sql-import-dialog"
    >
      <div class="sql-import-content">
        <p class="import-tip">
          请粘贴您的 CREATE TABLE 语句：
        </p>
        <el-input
          v-model="sqlInputValue"
          type="textarea"
          :rows="18"
          placeholder="例如：
CREATE TABLE users (
  id INT PRIMARY KEY AUTO_INCREMENT,
  username VARCHAR(50) NOT NULL COMMENT '用户名',
  email VARCHAR(100) COMMENT '邮箱',
  phone VARCHAR(20) COMMENT '手机号',
  department_id INT COMMENT '部门ID',
  status BOOLEAN DEFAULT TRUE COMMENT '用户状态',
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间'
);

CREATE TABLE departments (
  id INT PRIMARY KEY AUTO_INCREMENT,
  name VARCHAR(100) NOT NULL COMMENT '部门名称',
  parent_id INT COMMENT '上级部门ID',
  company_id INT NOT NULL COMMENT '公司ID',
  description TEXT COMMENT '部门描述',
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间'
);

支持一次导入多个表，系统会自动解析表结构、字段类型、注释和关联关系。"
          class="sql-textarea"
        />
      </div>

      <template #footer>
        <el-button @click="handleCancelImportSQL">
          取消
        </el-button>
        <el-button type="primary" @click="handleConfirmImportSQL">
          <el-icon><Upload /></el-icon>
          导入
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import type { DataTable } from "../types"
import { Connection, Delete, Download, Edit, Grid, Plus, Refresh, Search, Setting, Share, Upload } from "@element-plus/icons-vue"
import { ElMessage, ElMessageBox } from "element-plus"
import { computed, onMounted, reactive, ref } from "vue"
import { useRouter } from "vue-router"
import { databaseApi } from "@/common/apis"

const router = useRouter()

// 响应式数据
const loading = ref(false)
const tables = ref<DataTable[]>([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const sqlInputValue = ref("")
const sqlImportDialogVisible = ref(false)

// 搜索表单
const searchForm = reactive({
  name: ""
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表单数据
const tableForm = reactive({
  id: "",
  name: "",
  comment: ""
})

// 表单验证规则
const tableFormRules = {
  name: [
    { required: true, message: "请输入表名", trigger: "blur" },
    { pattern: /^[a-z][a-z0-9_]*$/, message: "表名必须以小写字母开头，只能包含小写字母、数字和下划线", trigger: "blur" }
  ],
  comment: [
    { required: true, message: "请输入表注释", trigger: "blur" }
  ]
}

// 表单引用
const formRef = ref()

// 计算属性
const dialogTitle = computed(() => isEdit.value ? "编辑数据表" : "新增数据表")

const filteredTables = computed(() => {
  let result = tables.value

  if (searchForm.name) {
    result = result.filter(table =>
      table.name.toLowerCase().includes(searchForm.name.toLowerCase())
      || table.comment.includes(searchForm.name)
    )
  }

  pagination.total = result.length
  const start = (pagination.currentPage - 1) * pagination.pageSize
  return result.slice(start, start + pagination.pageSize)
})

// 方法
async function loadTables() {
  loading.value = true
  try {
    const response = await databaseApi.getImportedTables({
      current: pagination.current,
      size: pagination.size,
      tableName: searchForm.name
    })

    // 将后端数据格式转换为前端需要的格式
    tables.value = response.data.records.map((dbTable: any) => ({
      id: dbTable.tableId?.toString() || dbTable.id?.toString() || "",
      name: dbTable.tableName || dbTable.name || "",
      comment: dbTable.tableComment || dbTable.comment || "",
      fields: dbTable.fields || [],
      createdAt: dbTable.createTime || dbTable.createdAt || "",
      updatedAt: dbTable.updateTime || dbTable.updatedAt || ""
    })) as DataTable[]

    pagination.total = response.data.total
    pagination.current = response.data.current
    pagination.pages = response.data.pages
  } catch (error) {
    console.error("加载数据表失败:", error)
    ElMessage.error("加载数据表失败，请稍后重试")
    tables.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

function getRelationCount(table: DataTable): number {
  return table.fields?.filter(field => field.relation?.enabled).length || 0
}

function handleSearch() {
  pagination.currentPage = 1
}

function handleReset() {
  searchForm.name = ""
  pagination.currentPage = 1
}

function handleSizeChange(size: number) {
  pagination.pageSize = size
  pagination.currentPage = 1
}

function handleCurrentChange(page: number) {
  pagination.currentPage = page
}

function handleAddTable() {
  isEdit.value = false
  dialogVisible.value = true
  resetTableForm()
}

function handleEditTable(table: DataTable) {
  isEdit.value = true
  dialogVisible.value = true
  tableForm.id = table.id
  tableForm.name = table.name
  tableForm.comment = table.comment
}

async function handleDeleteTable(table: DataTable) {
  try {
    await ElMessageBox.confirm(
      `确定要删除数据表 "${table.name}" 吗？删除后不可恢复。`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    )

    await databaseApi.deleteTables([table.id])
    ElMessage.success("删除成功")
    // 重新加载数据
    await loadTables()
  } catch (error: any) {
    if (error !== "cancel") {
      console.error("删除数据表失败:", error)
      ElMessage.error("删除失败，请稍后重试")
    } else {
      ElMessage.info("已取消删除")
    }
  }
}

function handleConfigTable(table: DataTable) {
  router.push(`/api-generator/table-config/${table.id}`)
}

function handleViewRelations(table: DataTable) {
  const relations = table.fields.filter(field => field.relation?.enabled)
  if (relations.length === 0) {
    ElMessage.info("该表暂无关联关系")
    return
  }

  const relationInfo = relations.map(field =>
    `${field.name} -> ${field.relation?.targetTableName}.${field.relation?.targetFieldName} (${field.relation?.type})`
  ).join("\n")

  ElMessageBox.alert(relationInfo, `${table.name} 的关联关系`, {
    confirmButtonText: "确定"
  })
}

async function handleSubmitTable() {
  try {
    await formRef.value?.validate()

    if (isEdit.value) {
      // 编辑表
      const index = tables.value.findIndex(t => t.id === tableForm.id)
      if (index > -1) {
        tables.value[index] = {
          ...tables.value[index],
          name: tableForm.name,
          comment: tableForm.comment,
          updatedAt: new Date().toLocaleString()
        }
        ElMessage.success("编辑成功")
      }
    } else {
      // 新增表
      const newTable: DataTable = {
        id: tableForm.name,
        name: tableForm.name,
        comment: tableForm.comment,
        fields: [],
        createdAt: new Date().toLocaleString(),
        updatedAt: new Date().toLocaleString()
      }
      tables.value.unshift(newTable)
      ElMessage.success("新增成功")
    }

    dialogVisible.value = false
    resetTableForm()
  } catch (error) {
    console.error("表单验证失败:", error)
  }
}

function resetTableForm() {
  tableForm.id = ""
  tableForm.name = ""
  tableForm.comment = ""
  formRef.value?.clearValidate()
}

function handleImportSQL() {
  sqlInputValue.value = ""
  sqlImportDialogVisible.value = true
}

function handleConfirmImportSQL() {
  if (sqlInputValue.value.trim()) {
    const parsedTables = parseSQLToTables(sqlInputValue.value)
    if (parsedTables.length > 0) {
      tables.value.push(...parsedTables)
      ElMessage.success(`成功导入 ${parsedTables.length} 个数据表`)
      sqlImportDialogVisible.value = false
      sqlInputValue.value = ""
    } else {
      ElMessage.warning("未解析到有效的表结构，请检查SQL语法")
    }
  } else {
    ElMessage.warning("请输入SQL语句")
  }
}

function handleCancelImportSQL() {
  sqlImportDialogVisible.value = false
  sqlInputValue.value = ""
}

function handleExportSQL() {
  if (tables.value.length === 0) {
    ElMessage.warning("暂无数据表可导出")
    return
  }

  const sqlScript = generateSQLScript(tables.value)

  // 创建下载链接
  const blob = new Blob([sqlScript], { type: "text/plain;charset=utf-8" })
  const url = URL.createObjectURL(blob)
  const link = document.createElement("a")
  link.href = url
  link.download = `database_schema_${new Date().toISOString().slice(0, 10)}.sql`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  URL.revokeObjectURL(url)

  ElMessage.success("SQL 脚本导出成功")
}

// SQL解析函数
function parseSQLToTables(sql: string): DataTable[] {
  const tables: DataTable[] = []

  // 简单的SQL解析（实际项目中可以使用更强大的SQL解析库）
  const createTableRegex = /CREATE\s+TABLE\s+(\w+)\s*\(([\s\S]*?)\)/gi
  let match

  while ((match = createTableRegex.exec(sql)) !== null) {
    const tableName = match[1]
    const fieldsStr = match[2]

    const fields: any[] = []
    const fieldLines = fieldsStr.split(",").map(line => line.trim())

    fieldLines.forEach((line) => {
      if (line && !line.toUpperCase().includes("PRIMARY KEY") && !line.toUpperCase().includes("FOREIGN KEY")) {
        const parts = line.split(/\s+/)
        if (parts.length >= 2) {
          const fieldName = parts[0].replace(/[`"']/g, "")
          const fieldType = parts[1].toUpperCase()

          fields.push({
            id: fieldName,
            name: fieldName,
            type: mapSQLTypeToFieldType(fieldType),
            required: line.toUpperCase().includes("NOT NULL"),
            isPrimary: line.toUpperCase().includes("PRIMARY KEY") || fieldName === "id",
            autoIncrement: line.toUpperCase().includes("AUTO_INCREMENT"),
            comment: extractComment(line) || fieldName
          })
        }
      }
    })

    tables.push({
      id: tableName,
      name: tableName,
      comment: tableName,
      fields,
      createdAt: new Date().toLocaleString(),
      updatedAt: new Date().toLocaleString()
    })
  }

  return tables
}

// SQL类型映射
function mapSQLTypeToFieldType(sqlType: string): string {
  if (sqlType.includes("INT") || sqlType.includes("BIGINT") || sqlType.includes("SMALLINT")) return "number"
  if (sqlType.includes("VARCHAR") || sqlType.includes("CHAR") || sqlType.includes("TEXT")) return "string"
  if (sqlType.includes("BOOLEAN") || sqlType.includes("BOOL")) return "boolean"
  if (sqlType.includes("DATE")) return "date"
  if (sqlType.includes("TIMESTAMP") || sqlType.includes("DATETIME")) return "datetime"
  if (sqlType.includes("JSON")) return "json"
  if (sqlType.includes("TEXT") || sqlType.includes("LONGTEXT")) return "text"
  return "string"
}

// 提取注释
function extractComment(line: string): string {
  const commentMatch = line.match(/COMMENT\s+['"`]([^'"`]*)['"`]/i)
  return commentMatch ? commentMatch[1] : ""
}

// 生成SQL脚本
function generateSQLScript(tables: DataTable[]): string {
  let script = "-- 数据库结构导出\n"
  script += `-- 生成时间: ${new Date().toLocaleString()}\n\n`

  tables.forEach((table) => {
    script += `-- ${table.comment}\n`
    script += `CREATE TABLE \`${table.name}\` (\n`

    const fieldLines: string[] = []
    let primaryKeys: string[] = []

    table.fields.forEach((field) => {
      let line = `  \`${field.name}\` ${getSQLType(field)}`

      if (field.autoIncrement) line += " AUTO_INCREMENT"
      if (field.required) line += " NOT NULL"
      if (field.defaultValue) line += ` DEFAULT '${field.defaultValue}'`
      if (field.comment) line += ` COMMENT '${field.comment}'`

      fieldLines.push(line)

      if (field.isPrimary) {
        primaryKeys.push(field.name)
      }
    })

    if (primaryKeys.length > 0) {
      fieldLines.push(`  PRIMARY KEY (\`${primaryKeys.join("`, `")}\`)`)
    }

    script += fieldLines.join(",\n")
    script += `\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='${table.comment}';\n\n`
  })

  return script
}

// 获取SQL类型
function getSQLType(field: any): string {
  switch (field.type) {
    case "number":
      return field.isPrimary ? "INT" : "INT"
    case "string":
      return field.length ? `VARCHAR(${field.length})` : "VARCHAR(255)"
    case "boolean":
      return "BOOLEAN"
    case "date":
      return "DATE"
    case "datetime":
      return "TIMESTAMP"
    case "text":
      return "TEXT"
    case "json":
      return "JSON"
    default:
      return "VARCHAR(255)"
  }
}

// 生命周期
onMounted(() => {
  loadTables()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.page-container {
  min-height: calc(100vh - 120px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: #303133;
}

.search-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.count-display {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 4px 8px;
  background-color: #f8f9fa;
  border-radius: 16px;
  border: 1px solid #e4e7ed;
}

.count-icon {
  font-size: 16px;
}

.count-number {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  min-width: 20px;
  text-align: center;
}

/* 弹出框样式隔离 */
:deep(.table-dialog .el-dialog__body) {
  padding: 20px;
}

:deep(.table-dialog .el-form-item__label) {
  font-weight: 500;
  color: #303133;
}

/* SQL导入对话框样式 */
:deep(.sql-import-dialog .el-dialog__body) {
  padding: 20px;
}

.sql-import-content {
  width: 100%;
}

.import-tip {
  margin: 0 0 15px 0;
  color: #606266;
  font-size: 14px;
  font-weight: 500;
}

.sql-textarea {
  width: 100%;
}

:deep(.sql-textarea .el-textarea__inner) {
  font-family: "Consolas", "Monaco", "Courier New", monospace;
  font-size: 13px;
  line-height: 1.5;
  border-radius: 8px;
  border: 1px solid #dcdfe6;
  background-color: #fafafa;
  resize: vertical;
  min-height: 400px;
}

:deep(.sql-textarea .el-textarea__inner:focus) {
  border-color: #409eff;
  background-color: #ffffff;
}

:deep(.sql-textarea .el-textarea__inner::placeholder) {
  color: #a8abb2;
  font-size: 12px;
}
</style>
